package com.javacv.plus.extensions.audio.steps;

import com.javacv.plus.core.processor.ProcessorContext;
import com.javacv.plus.core.processor.ProcessorStep;
import com.javacv.plus.extensions.audio.AudioProcessor;
import com.javacv.plus.extensions.audio.AudioResult;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.Frame;
import java.nio.Buffer;
import java.nio.ShortBuffer;

/**
 * 均衡器步骤
 */
@Slf4j
public class EqualizerStep implements ProcessorStep<AudioProcessor, AudioResult> {
    private final double[] bands;

    public EqualizerStep(double[] bands) {
        this.bands = bands;
    }

    @Override
    public AudioResult execute(AudioProcessor processor, ProcessorContext context) throws Exception {
        log.info("Applying equalizer with {} bands", bands.length);

        FFmpegFrameGrabber grabber = (FFmpegFrameGrabber) context.getAttribute("grabber");
        try (FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(
                "temp_equalizer.mp3",
                grabber.getAudioChannels(),
                grabber.getSampleRate()
        )) {
            recorder.setFormat(grabber.getFormat());
            recorder.setAudioBitrate(grabber.getAudioBitrate());
            recorder.setAudioChannels(grabber.getAudioChannels());
            recorder.setSampleRate(grabber.getSampleRate());
            recorder.start();

            // 处理音频帧
            while (true) {
                Frame frame = grabber.grab();
                if (frame == null) {
                    break;
                }

                if (frame.samples != null) {
                    for (int i = 0; i < frame.samples.length; i++) {
                        Buffer buf = frame.samples[i];
                        if (buf instanceof ShortBuffer) {
                            ShortBuffer sb = (ShortBuffer) buf;
                            int samplesPerBand = sb.limit() / bands.length;
                            for (int j = 0; j < sb.limit(); j++) {
                                int bandIndex = j / samplesPerBand;
                                if (bandIndex < bands.length) {
                                    short value = sb.get(j);
                                    value = (short) (value * bands[bandIndex]);
                                    sb.put(j, value);
                                }
                            }
                        }
                    }
                }

                recorder.record(frame);
            }
        }

        // 更新上下文
        context.setAttribute("grabber", new FFmpegFrameGrabber("temp_equalizer.mp3"));
        log.info("Equalizer effect completed");
        return null;
    }

    @Override
    public String getStepName() {
        return "Equalizer";
    }
} 